<template>
  <a-drawer :open="open" :width="800" title="收费" destroy-on-close root-class-name="z-[1001]" @close="onCancel">
    <a-form :model="formState" class="cost-form-style pb-4 h-full flex flex-col" :label-col="{ style: { width: '100px' } }">
      <div class="flex flex-wrap">
        <div class="w-1/3">
          <span class="text-lg font-bold">
            医疗费总额： <span class="text-xl">￥{{ formatAmount(businessData.ysje || 0) }}</span>
          </span>
        </div>
        <div class="w-1/3">
          <!-- <span v-if="isChs" class="text-lg font-bold">
            医保支付： <span class="text-xl">￥{{ formatAmount(businessData.outPocketAmountResponse?.ybzf || 0) }}</span>
          </span> -->
          <template v-if="systemConfig.isChs">
            <span class="text-lg font-bold">医保支付: </span>
            <span class="text-xl font-bold">￥{{ formatAmount(businessData.outPocketAmountResponse?.ybzf || 0) }}</span>
            <a-popover v-if="businessData.preSettlementInfo" trigger="click">
              <template #content> <CHSPopover :data="businessData.preSettlementInfo?.medicareAmountResponse" /> </template>
              <a-button size="small" class="ml-2" shape="circle">
                <span class="text-sm">?</span>
              </a-button>
            </a-popover>
          </template>
        </div>
        <div v-if="isYsje" class="w-1/3 text-right text-lg font-bold">
          应收金额：
          <span class="text-red-500 text-xl font-bold">￥{{ formatAmount(businessData.outPocketAmountResponse?.ssje ?? businessData.ysje) }}</span>
        </div>
      </div>
      <a-divider v-if="isYsje" />
      <div v-if="systemConfig.isCoupon && isDiscount">
        <CouponCard :br-id="brId" :medical-price="formState.ssje" class="mt-2" @success="onSuccessCoupon" />
        <a-divider />
      </div>
      <div v-if="isDispose">
        <div class="flex justify-between items-center">
          <BaseTitle title="预收款" class="!mb-0 !w-[90px]" />
          <div class="flex justify-end items-center">
            预收款：<span class="text-red-500 font-bold">￥{{ formatAmount(disposePrice) }}</span>
          </div>
        </div>
        <a-checkbox-group v-if="disposeData.length" v-model:value="chargeDepositlsh" class="w-full mt-4" @change="onDisposeChange">
          <a-checkbox v-for="(item, index) in disposeData" :key="index" :value="item.lsh" :disabled="item.disabled" class="w-full mb-3">
            <div class="w-full flex justify-between">
              <span>单号 {{ item.lsh }}</span>
              <span class="font-bold">￥{{ formatAmount(item.yjje) }}</span>
            </div>
          </a-checkbox>
        </a-checkbox-group>
      </div>
      <a-divider v-if="isDispose" />
      <div v-if="isFb" class="flex justify-between items-center">
        <BaseTitle title="分币误差" class="!mb-0 !w-[90px]" />
        <div>
          分币：<span class="text-red-500 font-bold">￥{{ formatAmount(formState.fbwc) }}</span>
        </div>
      </div>
      <a-divider v-if="isFb" />
      <div class="flex justify-end items-center text-lg font-bold">
        实收金额：<span class="text-red-500 text-xl">￥{{ formatAmount(formState.ssje) }}</span>
      </div>
      <a-divider />
      <div class="flex-1 flex flex-col">
        <a-radio-group v-if="systemConfig.isOpenPayCode" v-model:value="payType" button-style="solid" size="large" class="w-full flex px-8">
          <a-radio-button value="1">普通支付</a-radio-button>
          <a-radio-button value="2">扫码支付</a-radio-button>
        </a-radio-group>
        <div v-if="payType === '1'" class="flex flex-wrap mt-6 flex-1 content-start overflow-auto">
          <template v-for="item in chargeWayList" :key="item.id">
            <a-form-item v-if="!item.disabled" :label="item.zffsmc" class="w-1/2">
              <a-input-group class="!flex">
                <a-input
                  :key="item.zffsdm"
                  v-model:value="formState[item.zffsdm]"
                  v-input-selection
                  size="large"
                  placeholder="0.00"
                  :disabled="item.disabled || formState.ssje === 0"
                  @blur="onBlur(item.zffsdm)"
                  @change="handlerChangePrice(item.zffsdm)"
                >
                  <template #prefix> <span class="text-gray-400">￥</span> </template>
                </a-input>
                <a-button class="!w-10 !rounded-l-none" :disabled="item.disabled || formState.ssje === 0" size="large" @click="onClickAllAmount(item)">
                  <template #icon><ArrowLeftOutlined class="text-gray-400 text-xs" /></template>
                </a-button>
              </a-input-group>
            </a-form-item>
          </template>
        </div>
        <div v-else class="h-60 mt-6 px-8">
          <a-input ref="payCodeInputRef" v-model:value="payCode" size="large" placeholder="扫码支付" @keyup.enter="onOk" />
        </div>
      </div>
      <a-divider />
      <div class="flex justify-end items-center">
        <div class="mr-4">
          找零
          <span class="text-red-500 font-bold">
            ￥ <span class="pl-1">{{ formatAmount(formState.changeAmount) }}</span>
          </span>
        </div>
        <div>
          <a-button type="default" class="mr-2" size="large" @click="onCancel">取消</a-button>
          <a-button type="primary" :disabled="disabledState && !payCode && formState.ssje !== 0" :loading="loading" size="large" @click="onOk">确定</a-button>
        </div>
      </div>
    </a-form>
  </a-drawer>
</template>
<script setup>
import { onMounted, ref, watch } from 'vue'
import { ArrowLeftOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { post } from '@/utils/request'
import CouponCard from '@/components/CouponCard'
import { formatAmount } from '@/utils/format.js'
import { getSystemConfig } from '@/utils/systemConfig'

const emit = defineEmits(['update:open', 'success'])
const props = defineProps({
  open: Boolean,
  brId: {
    type: String,
    desc: '病人Id 用于获取优惠券',
    default: ''
  },
  sourceType: {
    desc: '收费类型',
    type: String,
    default: '0' //0  门诊 1 住院  2 视光
  },
  businessData: {
    type: Object,
    desc: '业务数据',
    default: () => ({})
  },
  inplsh: {
    type: String,
    default: ''
  },
  isDiscount: {
    desc: '是否优惠',
    type: Boolean,
    default: true
  },
  isFb: {
    desc: '是否显示分币',
    type: Boolean,
    default: true
  },
  isDispose: {
    desc: '是否显示押金预收款',
    type: Boolean,
    default: false
  },
  isYsje: {
    desc: '是否显示应收金额',
    type: Boolean,
    default: true
  }
})

const chargeWayList = ref([])
const loading = ref(false)
const formState = ref({
  zje: 0, // 医疗费总额：
  ysje: 0, // 应收金额
  ssje: 0, // 实收金额
  fbwc: 0, // 分币
  patientCouponsId: '', // 优惠券的id
  couponAmount: 0, // 抵用券金额
  changeAmount: 0 // 找零
})
// const realAmount = ref(0) // 实收金额
const payType = ref('1')
const payCode = ref()
const ePayTotal = ref(0) // 电子支付的总和
const priceAll = ref(0) // 全部的总和
const disabledState = ref(true)
const systemConfig = ref({})

// 找零=现金+电子支付-实收金额
const onCalcChange = () => {
  const change = +formState.value['xjzf'] + ePayTotal.value - Number(formState.value.ssje)
  formState.value.changeAmount = formatAmount(change < 0 ? 0 : change)
}
watch(
  () => formState.value.ssje,
  () => {
    nextTick(() => {
      let doneAmount = 0
      chargeWayList.value.forEach((list) => {
        if (list.zffsdm !== 'xjzf' && !list.disabled) {
          doneAmount += Number(formState.value[list.zffsdm] || 0)
        }
      })
      const change = +formState.value['xjzf'] + doneAmount - Number(formState.value.ssje)
      formState.value.changeAmount = formatAmount(change < 0 ? 0 : change)
    })
  }
)
const handlerChangePrice = (zffsdm = '') => {
  ePayTotal.value = 0
  priceAll.value = 0
  // 限制输入内容的范围
  formState.value[zffsdm] = formState.value[zffsdm].replace(/[^\d.]/g, '')
  // 计算电子支付的总和
  chargeWayList.value.forEach((list) => {
    if (list.zffsdm !== 'xjzf' && !list.disabled) {
      ePayTotal.value += Number(formState.value[list.zffsdm] || 0)
    }
  })
  ePayTotal.value = +formatAmount(ePayTotal.value)
  // 判断电子支付的总和是否大于实收金额
  if (ePayTotal.value > formState.value.ssje) {
    formState.value['xjzf'] = null
    formState.value.changeAmount = 0
    setTimeout(() => (formState.value[zffsdm] = ''), 100)
    return message.error('电子支付累计金额不可大于实收金额')
  }
  // 判断当前输入的是否是现金金额
  if (zffsdm === 'xjzf') {
    // 如果现金+电子支付>实收金额，计算找零
    if (+formState.value['xjzf'] + ePayTotal.value > +formState.value.ssje) {
      onCalcChange()
    } else {
      formState.value.changeAmount = 0
    }
  } else {
    // 判断电子支付金额是否等于0，如果不等于，判断实收金额是否大于电子支付金额或者是否相等
    if (ePayTotal.value !== 0) {
      if (formState.value.ssje > ePayTotal.value || formState.value.ssje === ePayTotal.value) {
        // 现金=实收金额-电子支付
        const cash = formState.value.ssje - ePayTotal.value < 0 ? 0 : formatAmount(formState.value.ssje - ePayTotal.value)
        formState.value['xjzf'] = +cash ? formatAmount(cash) : '0.00'
        onCalcChange()
      }
    } else {
      formState.value['xjzf'] = '0.00'
    }
  }

  for (const key in formState.value) {
    priceAll.value += Number(formState.value[key])
  }
  if (
    Number(formatAmount(priceAll.value)) > Number(formatAmount(formState.value.ssje)) ||
    Number(formatAmount(priceAll.value)) === Number(formatAmount(formState.value.ssje))
  ) {
    disabledState.value = false
  } else {
    disabledState.value = true
  }
}

// 判断优惠金额和支付，鼠标离开保留两位
const onBlur = (zffsdm = '') => {
  if (zffsdm !== '') {
    formState.value[zffsdm] = formState.value[zffsdm] ? formatAmount(formState.value[zffsdm]) : ''
  }
  // else {
  //   discountAmount.value = discountAmount.value ? formatAmount(discountAmount.value) : ''
  // }
}
// 单项全部收费
const onClickAllAmount = (item) => {
  formState.value['xjzf'] = ''
  formState.value[item.zffsdm] = ''
  let doneAmount = 0
  chargeWayList.value.forEach((list) => {
    if (list.zffsdm !== 'xjzf' && !list.disabled) {
      doneAmount += Number(formState.value[list.zffsdm] || 0)
    }
  })
  doneAmount = formatAmount(doneAmount)
  // chargeWayList.value.forEach((list) => !list.disabled && (formState.value[list.zffsdm] = ''))
  const lastAmount = Math.abs(formState.value.ssje) - doneAmount
  formState.value[item.zffsdm] = lastAmount > 0 ? formatAmount(lastAmount) : ''
  lastAmount > 0 && (formState.value.changeAmount = 0)
  disabledState.value = false
}
const onRest = () => {
  formState.value = {}
  formState.value.changeAmount = 0
  chargeDepositlsh.value = []
}
const disposeData = ref([])
const disposePrice = ref(0)
const chargeDepositlsh = ref([])
const onDisposeChange = () => {
  disposePrice.value = 0
  if (chargeDepositlsh.value.length > 0) {
    disposeData.value.forEach((item) => {
      if (chargeDepositlsh.value.indexOf(item.lsh) > -1) {
        disposePrice.value += Number(item.dpJe)
      }
    })
  }
  getRealityMoney(true)
}
const getChargeTypeList = async () => {
  const { code, data } = await post('/outp/oupCharge/getChargeTypeList')
  if (code !== 0) return
  chargeWayList.value = data.map((item) => {
    item.disabled = ['dyqzf', 'vipzf', 'yjzf'].includes(item.zffsdm)
    return item
  })
}

const onOk = async () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
  }, 3000)
  const discountAmount = Number(formState.value.zjyh || 0) + Number(formState.value.vipzf || 0) + Number(formState.value.couponAmount || 0)
  if (discountAmount > formState.value.ysje) {
    return message.error('优惠金额不能大于应收金额')
  }
  const chargeData = { ...formState.value }
  chargeWayList.value.forEach((item) => {
    chargeData[item.zffsdm] = chargeData[item.zffsdm] ? +chargeData[item.zffsdm] : 0
  })
  const params = {
    ...chargeData,
    barCode: payCode.value,
    zffs: payType.value,
    ybzf: props.businessData.outPocketAmountResponse?.ybzf || 0,
    // dyqno: formState.value.dyqno,
    // couponAmount: formState.value.couponAmount,
    // vipno: formState.value.vipno,
    change: formState.value.changeAmount,
    chargeDepositlsh: chargeDepositlsh.value,
    fbwc: formState.value?.fbwc
  }

  emit('success', params)
}

// 选择优惠券和会员卡
const onSuccessCoupon = async (id, price, state) => {
  switch (state) {
    case '优惠券':
      formState.value.dyqno = id
      formState.value.couponAmount = Number(price)
      chargeWayList.value.forEach((item) => {
        // if (item.zffsdm === 'dyqzf') {
        //   item.disabled = Number(price) > 0 ? true : false
        // }
        if (item.zffsdm !== 'vipzf') {
          formState.value[item.zffsdm] = null
        }
      })
      formState.value['dyqzf'] = Number(price) ? formatAmount(price) : null
      // setTimeout(() => {
      // }, 100)
      disabledState.value = false
      break
    case '会员卡':
      formState.value.vipno = id
      chargeWayList.value.forEach((item) => {
        // if (item.zffsdm === 'vipzf') {
        //   item.disabled = Number(price) > 0 ? true : false
        // }
        if (item.zffsdm !== 'dyqzf') {
          formState.value[item.zffsdm] = null
        }
      })
      formState.value['vipzf'] = Number(price) ? formatAmount(price) : null
      // setTimeout(() => {
      // }, 100)
      // chargeWayList.value.find((item) => item.zffsdm === 'vipzf').disabled = true
      disabledState.value = false
      break
    case '直接优惠':
      formState.value.zjyh = Number(price)
      disabledState.value = false
      break
  }
  await getRealityMoney()
}

//计算实收&分币
const getRealityMoney = async (isDispose) => {
  formState.value['yjzf'] = formatAmount(disposePrice.value)
  const discountAmount = Number(formState.value.zjyh || 0) + Number(formState.value.vipzf || 0) + Number(formState.value.couponAmount || 0)
  if (discountAmount > formState.value.ysje - (formState.value.fbwc || 0) - disposePrice.value) {
    return message.error('优惠金额不能大于应收金额')
  }
  const { code, data, msg } = await post('/outp/oupCharge/getPennyDiscount', {
    ysje: props.businessData.outPocketAmountResponse?.ssje ?? props.businessData.ysje, //应收金额
    yhje: formState.value.zjyh || 0,
    vipzf: formState.value.vipzf || 0,
    // lsh: formState.value.deposit, // 押金单号
    chargeDepositlsh: chargeDepositlsh.value,
    patientCouponsId: formState.value.patientCouponsId, // 优惠券id
    offsetAmount: formState.value.couponAmount, // 优惠券金额
    jklb: props.sourceType === '1' ? '2' : '1' //1:门诊 2:住院
  })
  if (code !== 0) {
    disabledState.value = true
    isDispose && (chargeDepositlsh.value = [])
    return message.error(msg || '获取实收金额失败')
  }
  // disabledState.value = false
  formState.value.ssje = data.ssje || 0
  formState.value.fbwc = data.fbwc || 0
  formState.value.fbyh = data.fbwc || 0
  // chargeWayList.value.forEach((item) => {
  //   formState.value[item.zffsdm] = ''
  // })
}

//获取押金预收款列表
const getDisposeData = async () => {
  let res = {}
  if (props.sourceType === '0') {
    //门诊押金
    res = await post('/outp/mzdj/getDepositSlipList', {
      brId: props.brId,
      status: '0',
      settlementType: '1'
    })
  } else if (props.sourceType === '2') {
    //视光押金
    res = await post('/outp/mzdj/getDepositSlipListSgXsd', {
      brId: props.brId,
      ids: props.businessData.selectIds,
      status: '0'
    })
  } else if (props.sourceType === '1') {
    //住院押金
    res = await post('/inp/inpComprehensive/getChargeList', {
      inplsh: props.inplsh,
      statusList: [1, 2]
    })
  }
  if (res.code !== 0) return message.error(res.msg || '获取预收款列表失败')
  disposeData.value = res.data
  if (disposeData.value && disposeData.value.length > 0) {
    chargeDepositlsh.value = []
    disposeData.value.forEach((item) => {
      // 住院
      if (props.sourceType === '1') {
        item.yjje = item.dpJe
        // if (item.dpJe > (props.businessData.outPocketAmountResponse?.ssje ?? props.businessData.ysje)) {
        //   item.disabled = true
        // }
      } else {
        // 非住院
        if (item.dpJe > (props.businessData.outPocketAmountResponse?.ssje ?? props.businessData.ysje)) {
          item.disabled = true
        }
      }
    })
    // const result = closestAmount(disposeData.value, props.businessData.outPocketAmountResponse?.ssje ?? props.businessData.ysje)
    // disposePrice.value = result.closest
    // result.bestCombination.forEach((item) => {
    //   chargeDepositlsh.value.push(item.lsh)
    // })
  }
  getRealityMoney()
}
// const closestAmount = (coins, target) => {
//   let nowNum = target
//   let allNum = 0
//   const selectItem = []
//   coins = coins.sort((a, b) => b.dpJe - a.dpJe)
//   coins.forEach((item) => {
//     if (item.dpJe <= nowNum) {
//       selectItem.push(item)
//       nowNum = Number(nowNum - item.dpJe)
//       allNum += Number(item.dpJe)
//     }
//   })
//   return { closest: allNum, bestCombination: selectItem || [] }
// }

watch(
  () => props.open,
  (val) => {
    if (val) {
      getChargeTypeList()
      if (props.isDispose) {
        getDisposeData()
      } else {
        getRealityMoney()
      }
      // getDiscountAmount()
      disabledState.value = true
      payCode.value = ''
      payType.value = '1'
    }
    onRest()
  },
  { immediate: true }
)
const payCodeInputRef = ref()

watch(
  payType,
  (val) => {
    payCode.value = ''
    setTimeout(() => val === '2' && payCodeInputRef.value?.focus(), 100)
  },
  { immediate: true }
)

const onCancel = () => {
  emit('update:open', false)
}
onMounted(() => {
  systemConfig.value = {
    isOpenPayCode: getSystemConfig('IS_CHARGE_SCAN_PAY') === '1', //扫码支付
    isCoupon: getSystemConfig('ENABLE_REGISTER_DISCOUNT') === '1', //收费标准
    isChs: getSystemConfig('IS_EXIST_MEDICAL_INSURANCE') === '1', //是否启用医保
    isChargeStandard: getSystemConfig('ENABLE_CHARGE_STANDARD_MODE') === '1' //启用挂号优惠功能
  }
})
</script>
<style lang="less" scoped>
:deep(.ant-radio-button-wrapper) {
  flex: 1;
  color: var(--primary-color);
  text-align: center;
  border-color: var(--primary-color);
  &::before {
    background-color: var(--primary-color);
  }
}

.cost-form-style {
  :deep(.ant-form-item) {
    padding: 0 3px;

    .ant-form-item-label {
      width: 75px;
      padding-top: 4px;
      label {
        color: #5d5d5d;
        font-size: 16px;
      }
    }
    .ant-form-item-control {
      flex: none;
      width: 240px;
      color: #2b2b2b;
      font-size: 15px;
      .ant-input {
        text-align: right;
      }
      .ant-btn {
        border-left-color: transparent;
      }
    }
  }
  .ant-divider {
    margin: 12px 0;
  }
}
.in-title {
  color: #a4adb3;
}
:deep(.ant-checkbox + span) {
  width: 100%;
}
</style>
